<style lang="scss">
.sep-line {
  text-align: center;
}
</style>

<script>
import pointsForm from '../pointsForm.vue'
import {
  toRange,
  toTime,
  getSeconds,
  formatter,
  rangeCheck,
  buildAvailableTimeRanges,

  Second,
  Minute,
  Hour,
  Day,
  overlapCheck
} from './utils'
export default {
  components: {
    pointsForm
  },
  props: {
    value: {
      type: Object,
      required: true,
      default() {
        return {
          form: {
            name: '',
            beginTime: null,
            endTime: null,
            number: 1
          },
          plans: []
        }
      }
    },
    isDeleteBtnVisible: {
      type: Boolean,
      required: false,
      default: true
    },
    isFormVisible: {
      type: Boolean,
      required: false,
      default: true
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  data() {
    return {
      visibleStatuses: {
        pointsList: false
      },

      points: [],

      formRules: {
        name: [{ type: 'string', required: true, message: '请输入班次名称', trigger: ['change', 'blur'] }]
      },

      pickerOptions: {
        selectableRange: []
      }

      // currentRowIndex: 0,
      // currentField: null
    }
  },
  computed: {
    plans: {
      get: function() {
        return this.value.plans
      },
      set: function(plans) {
        this.$emit('input', { form: this.form, plans })
      }
    },
    form: {
      get: function() {
        return this.value.form
      },
      set: function(form) {
        this.$emit('input', { form, plans: this.plans })
      }
    },
    patrolPlansSorted() {
      return this.plans.concat().sort((range1, range2) => {
        return range1.beginTime.getTime() - range2.endTime.getTime()
      })
    },
    patrolPlans() {
      return this.patrolPlansSorted.map((plan, index) => {
        const { beginTime, points } = plan
        return {
          key: beginTime.getTime(),
          label: `第${index + 1}个班次`,
          points,
          ...plan
        }
      })
    },
    availableTimeRanges() {
      // const { currentRowIndex, currentField } = this
      return []
    },
    colSizes() {
      if (this.isDeleteBtnVisible) {
        return {
          beginTime: 6,
          endTime: 6,
          number: 6,
          actionBtn: 3
        }
      }

      return {
        beginTime: 9,
        endTime: 9,
        number: 4,
        actionBtn: 0
      }
    }
  },
  mounted() {
    window.abcd = this.buildAvailableTimeRanges
  },
  methods: {
    buildAvailableTimeRanges(excludedIndexs) {
      const timeRangeOccupied = this.patrolPlans
        .filter((_, index) => {
          return !excludedIndexs.includes(index)
        })
        .map(item => {
          const { beginTime, endTime } = item
          return {
            beginSeconds: getSeconds(beginTime),
            endSeconds: getSeconds(endTime)
          }
        })

      const availableTimeRanges = buildAvailableTimeRanges(timeRangeOccupied)

      return availableTimeRanges.map(item => {
        return toRange(item.beginSeconds, item.endSeconds)
      })

      /**
       * 11:00:00 - 12:00:00
       * 空闲
       * 13:00:00 - 14:00:00
       * 没有空闲
       * 14:00:00 - 16:00:00
       */
    },
    handleTimePickerFocus(index, field) {
      console.log('聚焦', field)
    },
    handleTimePickerBlur(index, field) {
      console.log('失焦', field)
    },
    handleEditPoints(index) {
      if (index === undefined) {
        this.points = this.form.points
      } else {
        const timeRange = this.patrolPlans.at(index)
        if (!timeRange) return
        this.points = timeRange.points
      }

      this.visibleStatuses.pointsList = true
    },
    resetForm() {
      this.$emit('input', {
        form: {
          name: '',
          beginTime: null,
          endTime: null,
          points: []
        },
        plans: []
      })
    },
    isDate(o) {
      return o instanceof Date
    },
    validate() {
      return new Promise((resolve) => {
        this.$refs?.form.validate(flag => {
          if (!flag) {
            resolve(false)
            return
          }

          if (this.plans.length <= 0) {
            this.$message.error('至少添加一个班次')
            resolve(false)
            return
          }

          resolve(true)
        })
      })
    },
    timeRangeCheck() {
      const { beginTime, endTime, points } = this.form
      const { isDate, plans } = this

      if (!isDate(beginTime) || !isDate(endTime)) {
        throw new Error('请选择起始时间、结束时间')
      }

      const timeRange = {
        beginSeconds: getSeconds(beginTime),
        endSeconds: getSeconds(endTime)
      }

      const timeRanges = plans.map(item => {
        const { beginTime, endTime } = item
        return {
          beginSeconds: getSeconds(beginTime),
          endSeconds: getSeconds(endTime)
        }
      })

      rangeCheck(timeRange)
      overlapCheck(timeRanges, timeRange)

      if (!Array.isArray(points) || points.length <= 0) {
        throw new Error('至少添加一个点位')
      }
    },
    check2() {
      console.log(this.patrolPlansSorted)
    },
    addTimeRange() {
      try {
        console.log(this.form)
        const { beginTime, endTime, points } = this.form

        this.timeRangeCheck()

        this.plans.push({
          beginTime,
          endTime,
          points
        })

        this.form = {
          name: this.form.name,
          beginTime: null,
          endTime: null,
          points: []
        }
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    deleteTimeRange(plan) {
      if (this.plans.length <= 1) return this.$message.error('至少保留一个班次')
      this.$confirm('是否删除该班次', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.plans.findIndex(child => child.beginTime.getTime() === plan.beginTime.getTime())
        if (index === -1) return
        this.plans.splice(index, 1)
      })
    },
    savePoints(points) {
      console.log(points, this.form.points)
      this.visibleStatuses.pointsList = false
    }
  }
}
</script>

<template>
  <div>
    <el-form ref="form" :model="form" :rules="formRules" label-width="80px">

      <el-form-item label="班次简称" prop="name">
        <el-row :gutter="20">
          <el-col :span="23">
            <el-input v-model="form.name" :disabled="disabled" placeholder="请输入班次简称" />
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="班次列表">
        <el-row :gutter="20">
          <el-col :span="colSizes.beginTime">
            <div>开始时间</div>
          </el-col>

          <el-col class="sep-line" :span="1">-</el-col>

          <el-col :span="colSizes.endTime">
            <div>截至时间</div>
          </el-col>

          <el-col :span="colSizes.number">
            <div>点位编辑(数量)</div>
          </el-col>

          <el-col v-if="isDeleteBtnVisible" :span="colSizes.actionBtn">
            <div>操作</div>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item v-for="(plan,index) in patrolPlans" :key="plan.key" :label="plan.label">
        <el-row :gutter="20">
          <el-col :span="colSizes.beginTime">
            <el-time-picker
              v-model="plan.beginTime"
              disabled
              placeholder="起始时间"
              style="width: 100%;"
              @focus="handleTimePickerFocus(index,'BeginTime')"
              @blur="handleTimePickerBlur(index,'BeginTime')"
            />
          </el-col>

          <el-col class="sep-line" :span="1">-</el-col>

          <el-col :span="colSizes.endTime">
            <el-time-picker
              v-model="plan.endTime"
              disabled
              placeholder="结束时间"
              style="width: 100%;"
              @focus="handleTimePickerFocus(index,'EndTime')"
              @blur="handleTimePickerBlur(index,'EndTime')"
            />
          </el-col>

          <el-col :span="colSizes.number">
            <el-button
              plain
              type="primary"
              icon="el-icon-edit-outline"
              @click="handleEditPoints(index)"
            >
              {{ plan.points.length }}
            </el-button>
          </el-col>

          <el-col v-if="isDeleteBtnVisible" :span="colSizes.actionBtn">
            <el-button
              plain
              type="danger"
              icon="el-icon-delete"
              @click="deleteTimeRange(plan)"
            />
          </el-col>
        </el-row>

      </el-form-item>

      <el-form-item v-if="isFormVisible" label="添加范围">

        <el-row :gutter="20">
          <el-col :span="colSizes.beginTime">
            <el-time-picker
              v-model="form.beginTime"
              :picker-options="pickerOptions"
              placeholder="起始时间"
              style="width: 100%;"
              @focus="handleTimePickerFocus(null,'BeginTime')"
              @blur="handleTimePickerBlur(null,'BeginTime')"
            />
          </el-col>

          <el-col class="sep-line" :span="1">-</el-col>

          <el-col :span="colSizes.endTime">
            <el-time-picker
              v-model="form.endTime"
              placeholder="结束时间"
              style="width: 100%;"
              @focus="handleTimePickerFocus(null,'EndTime')"
              @blur="handleTimePickerBlur(null,'EndTime')"
            />
          </el-col>

          <el-col :span="colSizes.number">
            <el-button
              plain
              type="primary"
              icon="el-icon-edit-outline"
              @click="handleEditPoints()"
            >
              {{ form.points.length }}
            </el-button>
          </el-col>

          <el-col :span="colSizes.actionBtn">
            <el-button
              plain
              type="primary"
              icon="el-icon-check"
              @click="addTimeRange"
            />
          </el-col>
        </el-row>

      </el-form-item>

    </el-form>

    <pointsForm
      v-model="visibleStatuses.pointsList"
      :data="points"
      :disabled="disabled"
      @confirm="savePoints"
    />
  </div>
</template>
